import {
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { AuthService } from './auth.service';
/**
 * @guard文件作用:守卫
 */

@Injectable()
export class JwtAuthGuard extends AuthGuard('jwt') {
  constructor() {
    // private authService: AuthService
    // private readonly userService: UserService, // private readonly authService: AuthService,
    super();
  }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const req = context.switchToHttp().getRequest();
    const res = context.switchToHttp().getResponse();
    /**
     * @如果白名单数组中存在路径
     */
    if (this.hasUrl(this.urlList, req.url)) return true;

    try {
      // 获取token
      const accessToken = req.get('Authorization');
      if (!accessToken) throw new UnauthorizedException('请先登录');
      // this.authService.verifyToken(accessToken)
    } catch (e) {
      console.log(e);
      return false;
    }
  }
  // 白名单数组
  private urlList: string[] = ['/auth/login', '/users/register'];

  // 验证该次请求是否为白名单内的路由
  private hasUrl(urlList: string[], url: string): boolean {
    let flag = false;
    if (urlList.indexOf(url) !== -1) {
      flag = true;
    }
    return flag;
  }
}
